<template>
<div>
  <section class="app-container calendar-list-container">
    <el-row class="role-main">
      <el-col :span="5" class="role-left">
        <section class="search-box">
          <section class="search">
            <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="input23">
            </el-input>
          </section>
          <section class="btn">
            <el-button size="mini" class="btn-button" type="primary" @click="addRole">新增角色</el-button>
          </section>
          <section class="menu-group" v-loading="onloading" element-loading-text="正在查询中。。。" >
            <template>
              <ul>
                <li v-for="group in menuGroupList" :key="group.id" >
                  <i class="iconfont ali-wenjianjia1"></i>
                  <el-button type="text" @click="findGroupUserList(group)">
                    <span>{{group.role_name}}</span>
                  </el-button>
                </li>
              </ul>
            </template>
          </section>
      </section>
      </el-col>
      <el-col :span="19" class="role-right" v-loading="loading" element-loading-text="正在查询中。。。">
        <el-row>
          <el-col class="group-title">
            <span>{{gropList.role_name}}({{roleLength}}人)</span>
             <i class="iconfont ali-bianji" @click="openGroup"></i>
          </el-col>
          <el-col class="group-status">
            <section style="text-align:right">
               <el-button class="filter-item" type="danger" size="small" @click="delRows">批量删除</el-button>
               <el-button size="mini" type="primary" @click="openMember" plain>添加成员</el-button>
            </section>
          </el-col>
        </el-row>
        <section class="group-table">
          <el-table :data="groupUserList" border stripe highlight-current-row @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="user_name" label="姓名"></el-table-column>
            <el-table-column prop="dept_name" label="部门"></el-table-column>
            <el-table-column prop="work_num" label="工号"></el-table-column>
            <el-table-column prop="phone" label="手机"></el-table-column>

          </el-table>
        </section>
      </el-col>
    </el-row>
  </section>
  <!-- 新增编辑角色模态框 -->
  <section>
    <el-dialog :title="roleSatte=='add'?'新增角色':'编辑角色'" :visible.sync="isShow.dept" width="600px">
      <el-form :model="editDeptForm" style="padding:0 40px;" ref="editDeptForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="role_name" :rules="filter_rules({required:true})">
          <el-input v-model="editDeptForm.role_name"></el-input>
        </el-form-item>
        <el-form-item label="授权菜单" :label-width="formLabelWidth">
          <section v-loading="treeloading" element-loading-text="正在查询中。。。">
            <el-tree :data="dataTreeList" node-key="id" ref="checkedNote"
            :default-checked-keys="defaultGroup" show-checkbox @check-change="handleCheckChange">
              <span slot-scope="{ node, data }">
                  <span>{{ data.menu_name }}</span>
              </span>
            </el-tree>
          </section>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow.dept = false">取 消</el-button>
        <el-button v-if="roleSatte!='add'" type="danger" @click="delDept">删 除</el-button>
        <el-button type="primary" @click="onSubmit('editDeptForm')">确 定</el-button>
      </span>
    </el-dialog>
  </section>
    <!-- 添加成员穿梭框 -->
  <section>
    <member-view ref="childInit" @saveUsers="saveUsers" @closeTransfer="isShow.transfer = false" :isShow="isShow.transfer"></member-view>
  </section>
</div>

</template>
<script>
import { get_RoleList, add_Role, edit_Role, del_Role, add_UsersRole,deleteUsersRole } from "@/api/jurisdiction";
import { user_listAll, user_deleteAll } from "@/api/user";
import { menu_getTree } from "@/api/menu";
import member_transfer from "@/views/sysSet/components/add_member_transfer";

export default {
  components: { "member-view": member_transfer },
  name: "Role",
  data() {
    return {
      onloading: false,
      loading: false,
      treeloading: false,
      isShow: { add: false, dept: false, child: false, transfer: false },
      editDeptForm: {},
      formLabelWidth: "100px",
      roleSatte: "",
      menuGroupList: [],
      //表格数据
      groupUserList: [],
      multipleSelection: [],
      input23: "",
      gropList: {},
      roleLength: "",
      dataTreeList: [],
      defaultGroup: []
    };
  },
  methods: {
    async findGroupUserList(group) {
      this.gropList = group;
      let listTree = group.menu_ids;
      listTree = listTree.substr(0, listTree.length - 1);
      this.defaultGroup = listTree.split(",");
      this.roleList();
    },
    handleSelectionChange(e) {
      this.multipleSelection = e;
      console.log(`this.multipleSelection`,this.multipleSelection)
    },
    addRole() {//新增角色
      this.isShow.dept = true;
      this.editDeptForm = {}; //清空数据
      this.defaultGroup = []; //清空默认选择的菜单树结构
      this.dataTreeList = [];
      this.roleSatte = "add";
      this.treeList();
    },
    async delRows(){//删除角色里面的人
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      const role_id = this.gropList.id
      const query = {ids,role_id, company_id: localStorage.getItem("companyId") - 0};

      try {
        const res = await this.$confirm("确认删除吗？");
         if (res == "confirm") {
          this.loading = true;
          const {data} = await deleteUsersRole(query)
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {

      }
    },

    openGroup() {//编辑角色
      this.isShow.dept = true;
      this.roleSatte = "edit";
      this.defaultGroup = []; //清空默认选择的菜单树结构
      this.dataTreeList = [];
      this.treeList();
      this.editDeptForm = this.gropList;
      let listTree = this.gropList.menu_ids;
      this.defaultGroup = listTree.split(",");
    },
    openMember() {//打开添加成员模态框
      this.isShow.transfer = true;
      this.$refs.childInit.openTransfer();
    },
    handleCheckChange(e) {
      let key = this.$refs.checkedNote.getCheckedNodes();
      let ids = "";
      for (let i = 0; i < key.length; i++) {
        let element = key[i];
        ids += element.id + ",";
      }
      this.editDeptForm.menu_ids = ids;
    },
    async saveObj() {
      const query = {...this.editDeptForm, company_id: localStorage.getItem("companyId") - 0};
      this.onloading = true;
      const { data } = this.roleSatte == "add" ? await add_Role(query) : await edit_Role(query);
      this.onloading = false;
      if (data.status == 100) {
        this.$message.success(this.roleSatte == "add" ? "添加成功" : "编辑成功");
        this.editDeptForm = {}; //清空数据
        this.initList();
      }
    },
    async onSubmit(e) {//添加修改角色保存
      this.$refs[e].validate(valid => {
        if (valid) {
          this.saveObj();
          this.isShow.dept = false;
        } else {
          return false;
        }
      });
    },
    async delDept() {//删除角色
      try {
        let res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.onloading = true;
          let { data } = await del_Role({ id: this.editDeptForm.id });
          if (data.status == 100) {
            this.onloading = false;
            this.isShow.dept = false;
            this.$message.success("删除成功");
          }
          this.initList();

        }
      } catch (error) {}
    },
    async initList() {//获取角色数据
      const query = {company_id: localStorage.getItem("companyId") - 0}
      this.onloading = true;
      const { data } = await get_RoleList(query);
      this.onloading = false;
      if (data.status == 100) {
        this.menuGroupList = data.data.rows;
        this.gropList = data.data.rows[0];
        let listTree = this.gropList.menu_ids;
        this.defaultGroup = listTree.split(",");
        this.roleList();
      }
    },
    async roleList() {//获取角色成员数据
      const query = {role_id: this.gropList.id, company_id: localStorage.getItem("companyId") - 0}
      this.loading = true;
      const { data } = await user_listAll(query);
      this.loading = false;
      if (data.status == 100) {
        this.groupUserList = data.data.rows;
        this.roleLength = data.data.rows.length;
      }
    },
    async treeList() {//获取菜单树结构
      const query = {company_id: localStorage.getItem("companyId") - 0}
      this.treeloading = true;
      const { data } = await menu_getTree(query);
      this.treeloading = false;
      if (data.status == 100) {
        this.dataTreeList = data.data;
      }
    },
    async saveUsers(users) {//保存添加成员
      let ids = "";
      for (var i = 0; i < users.length; i++) {
        var element = users[i];
        let id = element.id.substring(7, element.id.length);
        ids += id + ",";
      }
      this.isShow.transfer = false;
      this.loading = true;
      let params = {
        company_id: localStorage.getItem("companyId"),
        user_ids: ids,
        role_id: this.gropList.id
      };
      let { data } = await add_UsersRole(params);
      this.loading = false;
      if (data.status == 100) {
        this.$message.success("添加成功");
        this.roleList();
      }
    }
  },
  created: function() {
    this.initList();
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.ali-wenjianjia1 {
  color: #b8e8ff;
}
.search-box {
  background-color: #fff;
  padding: 20px;
  margin-right: 20px;
  .btn {
    padding: 20px 0;
    width: 100%;
    text-align: center;
  }
  .btn-button {
    width: 100%;
  }
  .menu-group {
    overflow: hidden;
    background-color: #fff;
    // padding: 15px;
    span {
      color: #585858;
      font-size: 13px;
    }
  }
}
.role-right {
  padding: 40px;
  background-color: #fff;
  .group-title span {
    font-size: 18px;
  }
  .ali-bianji {
    color: orange;
    font-size: 23px;
    &:hover {
      cursor: pointer;
    }
  }
  .group-status {
    padding: 20px 0;
  }
}
.child-box {
  padding-left: 20px;
}
.group-box {
  padding-left: 20px;
  .el-checkbox {
    margin-left: 0;
    margin-right: 20px;
  }
}
</style>
